package com.example.a2209_mianshi.ui.login

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.example.a2209_mianshi.base.BaseViewModel
import com.example.a2209_mianshi.base.state.Failed
import com.example.a2209_mianshi.base.state.Loading
import com.example.a2209_mianshi.base.state.RequestEvent
import com.example.a2209_mianshi.base.state.Success
import com.example.a2209_mianshi.mmkv.AuthMMKV
import com.example.a2209_mianshi.ui.login.model.LoginMode
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class LoginViewModel @Inject constructor(
    private val mRepository: LoginRepository
)  :BaseViewModel() {
    //保存当前正在显示的fragment
    private val _currentFragment = MutableStateFlow("")
    val currentFragment: StateFlow<String>
        get() = _currentFragment
    //账号密码
//    val phone: MutableStateFlow<String> = MutableStateFlow(if (BuildConfig.DEBUG) "14726662983" else "")
//    val password: MutableStateFlow<String> = MutableStateFlow(if (BuildConfig.DEBUG) "111111" else "")
    val phone: MutableStateFlow<String> = MutableStateFlow("")
    val password: MutableStateFlow<String> = MutableStateFlow("")
    val restPassword: MutableStateFlow<String> = MutableStateFlow("")
    val confirmPassword: MutableStateFlow<String> = MutableStateFlow("")
    //channel 适合一对一，非粘性，可避免shareFlow订阅时间晚,丢失第一条信息的问题
    private val _requestSmsCodeEvent = Channel<RequestEvent>()
    val requestSmsCodeEvent get() = _requestSmsCodeEvent.receiveAsFlow()
    //登录请求事件
    private val _requestLoginEvent = MutableSharedFlow<RequestEvent>()
    val requestLoginEvent get() = _requestLoginEvent.asSharedFlow()
    //请求发送验证码的时间
    var sendSmsCodeTimeStamp: Long = 0L
    var requestRest: Boolean = false
    fun setShowingFragmentTag(tag: String) {
        _currentFragment.value = tag
    }
    fun resetSmsCodeEvent(success: Boolean) {
        viewModelScope.launch {
            _requestSmsCodeEvent.send(if (success) Success else Failed(""))
        }
    }
    //获取短信验证码
    fun getSmsCode(type: String) {
        execute(
            action = if (type == "login") {
//                mRepository.getLoginSmsCode(phone.value)
                mRepository.sendCodeLogin("2", phone.value)
            }else if (type == "rest") {
//                mRepository.getRestSmsCode(phone.value)
                mRepository.sendCodeLogin("2", phone.value)
            } else {
//                mRepository.getBindSmsCode(phone.value)
                mRepository.sendCodeLogin("2", phone.value)
            },
            onStart = {
                _requestSmsCodeEvent.send(Loading)
            },
            onError = {
                _requestSmsCodeEvent.send(Failed(it))
            },
            onFinish = {
                _requestSmsCodeEvent.send(Success)
                Log.d("loginViewModel", "cmallAdInfo:"+it.msg)
            })
    }
    //验证码登录
    fun loginBySmsCode(smsCode: Int){
        viewModelScope.launch {
            _requestLoginEvent.emit(Loading)
            mRepository.codeLogin(LoginMode.SMS,"",2,"",smsCode,phone.value).handleApiException2Model()
                .collect{
                    if (it.data == null){
                        _requestLoginEvent.emit(Failed(it.msg))
                        return@collect
                    }
                    //保存token
                    AuthMMKV.accessToken = (it.data.access_token as Map<*, *>)["access_token"] as String
                }
        }
    }
    fun clearRestPassword() {
        restPassword.value = ""

    }

    fun clearConfirmPassword() {
        confirmPassword.value = ""
    }

    fun clearPhone() {
        phone.value = ""
    }

    fun clearPassword() {
        password.value = ""
    }
}